﻿////////////////////////////////////////////////////////////////////////////////
// Source Copyright (C) J.Fan
// @author      J.Fan
// @date        2013-01-19
// @revision    Revision in Version Control System
// @remark      
////////////////////////////////////////////////////////////////////////////////

namespace JsonConverter.Converter
{
    /// <summary>
    /// Convert DateTime value to string with default or specified C# format pattern;
    /// </summary>
    public class DateTimeFormatConverter: IPrimitiveConverter
    {
        public const string DefaultFormat = "{0:yyyy-MM-dd HH:mm:ss}";

        private string formatPattern;
        public string FormatPattern { get { return formatPattern; } }

        public DateTimeFormatConverter() : this(null) { }

        public DateTimeFormatConverter(string formatPattern)
        {
            if (formatPattern == null)
            {
                formatPattern = DefaultFormat;
            }

            if (formatPattern.IndexOf('{') >= 0)
            {
                this.formatPattern = formatPattern;
            }
            else
            {
                this.formatPattern = string.Format("{{0:{0}}}", formatPattern);
            }
        }

        public string Convert(object value)
        {
            return StringConverter.ToJavascriptString(string.Format(formatPattern, value));
        }
    }
}
